package aufgabe1;

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

public class SierpinskiTeppich extends Frame {
	private static final long serialVersionUID = 7700479919667967835L;
	
	private double x = 50;
	private double y = 60;
	private double size = 729;
	
	private int ordnung = 5;
	
	public SierpinskiTeppich(int ordnung) {
		addWindowListener(new MyFinishWindow());
		this.ordnung = ordnung;
	}
	
	@Override
	public void paint(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		
		Rectangle2D.Double re2d = new Rectangle2D.Double(x, y, size, size);
		g2d.fill(re2d);
		
		drawSquare(g2d, x, y, size, 0);
	}
	
	public void drawSquare(Graphics2D g, double x, double y, double size, int run) {
		double newSize = size / 3;
		
		if(newSize <= 0 || run == ordnung) {
			return;
		}
		
		for(int i = 0; i < 9; i++) {
			if (i == 4) {
				g.clearRect((int)(x + ((i % 3) * newSize)), (int)(y + ((int)(i / 3) * newSize)), (int)newSize, (int)newSize);
				continue;
			}
			drawSquare(g, (x + ((i % 3) * newSize)), (y + ((int)(i / 3) * newSize)), newSize, run + 1);
		}
	}
	
	public static void main(String[] args) {
		SierpinskiTeppich t = new SierpinskiTeppich(10);
		t.setTitle("Sierpinski-Teppich");
		t.setSize(829, 829);
		t.setResizable(false);
		t.setVisible(true);
	}
}
